﻿using System;
using System.Text;
using System.Web.Mvc;
using VietPremier.Models;

namespace VietPremier.Repository
{
    public static class PagingHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
        {
            StringBuilder result = new StringBuilder();

            if (pagingInfo.CurrentPage > 1)
            {
                TagBuilder li = new TagBuilder("li"); // Construct an <li> tag
                TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(1)); // Tức dấu <<
                tag.InnerHtml = "<<";
                li.InnerHtml = tag.ToString(TagRenderMode.Normal);
                result.Append(li.ToString());

                li = new TagBuilder("li"); // Construct an <li> tag
                tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(pagingInfo.CurrentPage - 1)); // Tức dấu <
                tag.InnerHtml = "<";
                li.InnerHtml = tag.ToString(TagRenderMode.Normal);
                result.Append(li.ToString());
            }

            var start = Math.Max(pagingInfo.CurrentPage - 2, 1);
            var end = Math.Min(pagingInfo.TotalPages, pagingInfo.CurrentPage + 2);

            for (var i = start; i <= end; i++)
            {
                TagBuilder li = new TagBuilder("li"); // Construct an <li> tag
                TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(i));
                tag.InnerHtml = i.ToString();
                if (i == pagingInfo.CurrentPage)
                    li.AddCssClass("active");
                li.InnerHtml = tag.ToString(TagRenderMode.Normal);
                result.Append(li.ToString());

            }

            if (pagingInfo.CurrentPage < pagingInfo.TotalPages)
            {
                TagBuilder li = new TagBuilder("li");
                TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(pagingInfo.CurrentPage + 1)); // Tức dấu >
                tag.InnerHtml = ">";
                li.InnerHtml = tag.ToString(TagRenderMode.Normal);
                result.Append(li.ToString());

                li = new TagBuilder("li");// Construct an <li> tag
                tag = new TagBuilder("a"); // Construct an <a> tag
                tag.MergeAttribute("href", pageUrl(pagingInfo.TotalPages)); // Tức dấu >
                tag.InnerHtml = ">>";
                li.InnerHtml = tag.ToString(TagRenderMode.Normal);
                result.Append(li.ToString());
            }

            return MvcHtmlString.Create(result.ToString());
        }

    }
}